package com.ssy.lingxi.sms.serviceImpl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.sms.api.common.AliConfigEnum;
import com.ssy.lingxi.sms.api.common.AliErrorCodeEnum;
import com.ssy.lingxi.sms.api.common.ServiceTypeEnum;
import com.ssy.lingxi.sms.api.entity.SmsSendMsg;
import com.ssy.lingxi.sms.api.model.SmsVO;
import com.ssy.lingxi.sms.entity.SmsConfig;
import com.ssy.lingxi.sms.entity.Template;
import com.ssy.lingxi.sms.repository.TemplateRepository;
import com.ssy.lingxi.sms.service.IAliService;
import com.ssy.lingxi.sms.service.ISmsConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 短信发送
 * @author jw.chen
 * @version 2.0.0
 * @date 2021/10/26
 */
@Service
public class AliServiceImpl implements IAliService {

    @Autowired
    private ISmsConfigService smsConfigService;

    @Autowired
    private TemplateRepository templateRepository;

    /**
     * 发送短信
     * @param smsVO
     * @return
     */
    @Override
    public Wrapper<List<SmsSendMsg>> sendSms(SmsVO smsVO, SmsConfig smsConfig){
        String[] phones = smsVO.getPhones();
        //根据业务编号查找短信内容模板
        String code = smsVO.getCode();
        Template template = templateRepository.findFirstByCode(code);

        //定义返回对象
        List<SmsSendMsg> result = new ArrayList<>();

        if(template != null){
            //获取签名
            String signName = "";
            HashMap<String, Object> config = smsConfig.getConfig();
            Object signNameObj = config.get(AliConfigEnum.signName.getCode());
            if(signNameObj != null){
                signName = signNameObj.toString().substring(0, signNameObj.toString().indexOf(Constants.SPLIT_STR));
            }
            //获取参数
            String[] templateParam = smsVO.getTemplateParam();
            String templateContent = template.getTemplateContent();
            String jsonParam = getJsonParam(templateContent, templateParam);

            try {
                //获取客户端
                Client client = this.getSmsClient(smsConfig);

                //发送短信
                SendSmsRequest sendSmsRequest = new SendSmsRequest();
                sendSmsRequest.setPhoneNumbers(ArrayUtil.join(smsVO.getPhones(), ","));
                sendSmsRequest.setSignName(signName);
                sendSmsRequest.setTemplateCode(template.getTemplateId());
                if(jsonParam != null){
                    sendSmsRequest.setTemplateParam(jsonParam);
                }
                SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
                SendSmsResponseBody body = sendSmsResponse.getBody();
                String responseCode = body.getCode();
                if("OK".equals(responseCode)){
                    Arrays.stream(phones).forEach(phone -> {
                        SmsSendMsg smsSendMsg = new SmsSendMsg();
                        smsSendMsg.setPhone(phone);
                        smsSendMsg.setStatus(true);
                        result.add(smsSendMsg);
                    });
                }else{
                    Arrays.stream(phones).forEach(phone -> {
                        SmsSendMsg smsSendMsg = new SmsSendMsg();
                        smsSendMsg.setPhone(phone);
                        smsSendMsg.setCode(responseCode);
                        smsSendMsg.setMsg(AliErrorCodeEnum.getMessage(responseCode));
                        result.add(smsSendMsg);
                    });
                }
                return Wrapper.success(result);
            } catch (Exception e) {
                //获取错误提示信息
                String msg = e.getMessage();
                SmsSendMsg smsSendMsg = new SmsSendMsg();
                smsSendMsg.setCode(msg);
                smsSendMsg.setMsg(AliErrorCodeEnum.getMessage(msg));
                result.add(smsSendMsg);
                return Wrapper.fail(ResponseCode.SERVICE_ERROR, result);
            }
        }else{
            Arrays.stream(phones).forEach(phone -> {
                SmsSendMsg smsSendMsg = new SmsSendMsg();
                smsSendMsg.setPhone(phone);
                smsSendMsg.setCode(String.valueOf(ResponseCode.SMS_TEMPLATE_NOT_EXIST.getCode()));
                smsSendMsg.setMsg(ResponseCode.SMS_TEMPLATE_NOT_EXIST.getMessage());
                result.add(smsSendMsg);
            });
            return Wrapper.success(result);
        }
    }

    /**
     * 批量发送接口
     * @param smsVO
     * @param smsConfig
     * @return
     */
    @Override
    public Wrapper<?> sendBatchSms(SmsVO smsVO, SmsConfig smsConfig) {
        return null;
    }

    /**
     * 获取链接对象
     * @return
     */
    public Client getSmsClient(SmsConfig smsConfig) throws Exception {
        if(smsConfig == null){
            smsConfig = smsConfigService.getSmsConfig(ServiceTypeEnum.Ali.getCode());
        }
        //获取参数
        HashMap<String, Object> config = smsConfig.getConfig();
        String accessKeyId = "";
        String accessKeySecret = "";
        Object accessKeyIdObj = config.get(AliConfigEnum.accessKeyId.getCode());
        if(accessKeyIdObj != null){
            accessKeyId = accessKeyIdObj.toString().substring(0, accessKeyIdObj.toString().indexOf(Constants.SPLIT_STR));
        }
        Object accessKeySecretObj = config.get(AliConfigEnum.accessKeySecret.getCode());
        if(accessKeySecretObj != null){
            accessKeySecret = accessKeySecretObj.toString().substring(0, accessKeySecretObj.toString().indexOf(Constants.SPLIT_STR));
        }

        Config aliConfig = new Config().setAccessKeyId(accessKeyId).setAccessKeySecret(accessKeySecret);
        // 访问的域名
        aliConfig.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(aliConfig);
    }

    /**
     * 获取组装好的json参数
     * @param str 字符串
     * @return
     */
    private String getJsonParam(String str, String[] paramValue){
        JSONObject json = new JSONObject();
        int i = 0;
        String pattern = "\\{[^}]*}"; // 匹配{} 的表达式
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(str);
        while(m.find()){    // 当字符串中有匹配到 {} 时
            String param = m.group(0);  // {} 和里面的内容
            param = param.substring(1,param.length()-1);
            json.set(param, paramValue[i]);
            i++;
        }
        if(json.size() > 0){
            return json.toString();
        }else{
            return null;
        }
    }
}
